package com.shuai.chatroom.common;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 验证码工具类，用户向前端发送验证码，并验证验证码
 */
public class MyCaptchaUtils {

    /**
     * 返回验证码给前端
     */
    public static void sendCaptcha
    (HttpServletRequest request, HttpServletResponse response) throws IOException {
        //先获取验证码
//        ShearCaptcha shearCaptcha = CaptchaUtil.createShearCaptcha(100, 50, 4, 2);
        CircleCaptcha shearCaptcha = CaptchaUtil.createCircleCaptcha(80, 40, 4, 4);
        //将验证码的值存储session会话对象中，方便后来的验证
        request.getSession().setAttribute(AppConstant.CAPTCHA_KEY, shearCaptcha.getCode());
        //将验证码响应给前端浏览器
        response.setContentType("image/png");
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expire", 0);
        shearCaptcha.write(response.getOutputStream());
    }

    /**
     * 验证前端输入的验证码是否正确
     */
    public static boolean verifyCaptcha(HttpServletRequest request, String captcha) {
        HttpSession session = request.getSession(false);
        if (session == null) {
            return false;
        }
        Object attribute = session.getAttribute(AppConstant.CAPTCHA_KEY);
        if (attribute == null) {
            return false;
        }
        String correctCaptcha = (String) attribute;
        return correctCaptcha.equals(captcha);
    }

}
